import { login } from '@/api/index';
import ls from '@/util/ls';
import store from '@/store';


export default {
	namespaced:true, //解决命名冲突
	state:{
	 user:{
		mobile:"",
		nickName: "",
		openId: "",
		realName: "",
	    wxUserId:""
	 },
	 loginStatus:0,//0未登录 1登录
	 safeAreaInsetsBottom:34 //安全区域默认34
	},
	mutations:{
		clear(state){
		    ls.remove("user")
            ls.remove("token")
			state.user={
				mobile:"",
				nickName: "",
				openId: "",
				realName: "",
				wxUserId:""
			}
			state.loginStatus=0


		},
		setUser(state,user){
			
			state.user=user
			
		},
		setLoginStatus(state,status){
			
			state.loginStatus=status
		},
		setSafeAreaInsets(state,safeAreaInsets) { //获取安全区域
			const systemInfo = wx.getSystemInfoSync();
			
		// 	// 获取安全区域信息
			const safeArea = systemInfo.safeArea;
			const screenHeight = systemInfo.screenHeight;
			// 计算底部安全区域高度
		   const bottomSafeAreaHeight = screenHeight - safeArea.bottom;
		  
			state.safeAreaInsetsBottom=bottomSafeAreaHeight
		  
		
		}
		
	},
	actions:{

		wxlogin(context,e){
		return	new Promise((resolve,reject)=>{
			wx.login({
				success: (res) => {
					const code = res.code;
				
					// 获取社区ID，如果不为-1则传入
					const communityId = store.state.community.communityId;
					const loginParams = {
						loginCode: code,
						infoCode: e&&e.detail.code ||undefined,
						//  flag:"2"
					};
					
					// 如果社区ID不为-1，则添加到登录参数中
					if (communityId && communityId !== -1) {
						loginParams.communityId = communityId;
					}
					
					login(loginParams).then(datas => {

                       if(datas&&datas.token){
						context.commit('setLoginStatus',1)
						ls.set("token", datas.token)
						ls.set("user", datas)
						context.commit('setUser',datas)
						if(datas&&datas.token){ //如果有token则不跳转
							resolve({ 
								path:""
							})
						}else{//如果没有token则跳转登录
							resolve({
								path:"pages/login/index?login=2"
							})
						}
						
						
						if(e&&e.detail.code){
							if(e.detail.login&&e.detail.login==1){
								uni.switchTab({
									url: '/pages/home/index',
									
								});
							}else if(e.detail.login&&e.detail.login==2){
								
								uni.navigateBack()
							}
						}
					}else{
						resolve({
							path:"/pages/login/index"
						})
					}
					})
					}
				});
			})
			
		},
		isLogin(context){
		 return new Promise((resolve,reject)=>{
			let token=ls.get("token")
			if(token){
				resolve(true)
				}else{
					uni.showModal({
						title: "提示",
						content: "您暂未登录，是否前往登录",
						success: (res) => {
						  if (res.confirm) {
							uni.navigateTo({
							  url: "/pages/login/index"
							})  
						  }
						},
				
					  })
					resolve(false)
				}
				
			})
		}
	}
	
}